package com.xxx.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.Dao.BookDao;
import com.xxx.Dao.MenuDao;
import com.xxx.entity.Books;
import com.xxx.entity.Menu;
import com.xxx.service.BookService;
import com.xxx.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service("MenuService")
public class MenuServiceImpl extends ServiceImpl<MenuDao, Menu> implements MenuService {

    @Autowired
    BookService bookService;

    @Override
    public Menu getById(Integer id) {
        Assert.notNull(id,"id不能为空");
        return super.getById(id);
    }

    @Override
    public List<Menu> getAll() {
        List<Menu> list = super.list();

        Assert.notNull(list,"查询结果为空");

        List<Menu> resultList = getMenuTree(null,list);
        return resultList;
    }

    //获取叶子结点
    private List<Menu> getMenuTree(Menu parentMen,List<Menu> list) {
        int pid = 0;
        if(null != parentMen)
            pid = parentMen.getId();
        //查询所有节点，结果保存到tree中
        List<Menu> tree = new ArrayList<>();
        for (Menu menu : list) {
            if (menu.getParentId().equals(pid)){
                tree.add(menu);
            }
        }
        //如果子节点不为空，保存到parentMenu中，遍历子节点
        if(tree.size()>0){
            if(null != parentMen)
                parentMen.setTreeList(tree);
            for (Menu menu : tree) {
                getMenuTree(menu,list);
            }
        }
        return tree;
    }

    @Override
    public int saveMenu(Menu menu) {
        boolean save = super.save(menu);
        return save == true ? 1 : 0;
    }

    @Override
    public int update(Menu menu) {
        return super.updateById(menu)==true?1:0;
    }

    @Override
    public int delete(Integer id) {
        bookService.deleteByMenuId(id);
        boolean i = super.removeById(id);
        return i == true ? 1 : 0;
    }
}
